package com.itheima.springbootwebtest.service.impl;

import com.itheima.springbootwebtest.mapper.WareHouseMapper;
import com.itheima.springbootwebtest.pojo.WareHouse;
import com.itheima.springbootwebtest.pojo.WareHouseVO;
import com.itheima.springbootwebtest.service.WareHouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * TODO
 *
 * @Author mr.luo
 * @Date 13 4月 2025 16:25
 */
@Service
public class WareHouseServiceImpl implements WareHouseService {
    @Autowired
    private WareHouseMapper wareHouseMapper;

    @Override
    public List<WareHouse> select(WareHouse warehouseName) {
        List<WareHouse> list = wareHouseMapper.select(warehouseName);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<WareHouseVO> selectGetWarehouse(Integer restock) {
//        先查出来所有的库存
        List<WareHouse> list = wareHouseMapper.selectAll();
        list = list.stream().sorted((o1, o2) -> o2.getStock() - o1.getStock()).collect(Collectors.toList());
//        System.out.println(list);
        List<WareHouseVO> list1 = new ArrayList<>();
        for (WareHouse wareHouse : list) {
            if (wareHouse.getStock() <= restock) {
                restock = restock - wareHouse.getStock();
                WareHouseVO wareHouseVO = new WareHouseVO();
                wareHouseVO.setWarehouseName(wareHouse.getWarehouseName());
                wareHouseVO.setRestock(wareHouse.getStock());
                wareHouseVO.setBalance(0);
                wareHouseMapper.update(wareHouseVO);
                list1.add(wareHouseVO);
            } else {
                WareHouseVO wareHouseVO = new WareHouseVO();
                wareHouseVO.setWarehouseName(wareHouse.getWarehouseName());
                wareHouseVO.setRestock(restock);
                wareHouseVO.setBalance(wareHouse.getStock() - restock);
                wareHouseMapper.update(wareHouseVO);
                list1.add(wareHouseVO);
                break;
            }
        }
        //修改库存
//        wareHouseMapper.update(list1);
        return list1;
    }
}
